package com.example.controller;

import com.example.vo.MsgVo;
import com.example.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/*
 * @Author: hx
 * @CreateTime: 2022/3/2 09:45
 * @Description:
 * */
@RestController
@Slf4j
public class SMSController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SMSUtils smsUtils;

    @PostMapping("/captchas")
    public void sendMessage(@RequestBody MsgVo msgVo){
        //获取接受到的手机号
        String phone = msgVo.getPhone();
        log.info("发送的手机号码是{}",phone);
        //每次发送短信验证码时，判断该手机是否在有效期内
        String timeoutKey="timeout_"+phone;
        if (stringRedisTemplate.hasKey(timeoutKey)){
            throw new RuntimeException("不允许重复发送");
        }
        try {
            //生成4位随机字符
            String code = RandomStringUtils.randomNumeric(4);
            log.info("发送的验证码：{}",code);
            //根据输入的手机号发送对应的号码和验证码
            smsUtils.sendMsg(phone,code);
            //将验证码放入redis
            String phoneKey="phone_"+phone;
            stringRedisTemplate.opsForValue().set(phoneKey,code,10, TimeUnit.MINUTES);
            //如果验证码在有效期内，不允许重复发送
            stringRedisTemplate.opsForValue().set(timeoutKey,"true",60,TimeUnit.SECONDS);//两次发送间隔
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("提示：短信发送失败");
        }

    }
}
